

#include <cegfx/cexml.h>


ceXmlElement::ceXmlElement (xmlNode* node)
	: node (node)
{
	IQF_CONSTRUCT;
}

ceXmlElement::~ceXmlElement ()
{
}

IQF_IMPLEMENTATION_BEGIN(ceXmlElement);
IQF_IMPLEMENTATION_END();


const char* ceXmlElement::GetTagName () const
{
	return (const char*)node->name;
}

const char* ceXmlElement::GetAttribute (const char* name, const char* defaultValue) const
{
  if (!node)
    {
      return "";
    }

  for (xmlAttr* attr = node->properties; attr; attr = attr->next)
    {
      if (strcmp ((const char*)attr->name, name) == 0)
        {
          return (const char*)attr->children->content;
        }
    }
  return defaultValue;
}

bool ceXmlElement::HasAttribute (const char* name) const
{
  if (!node)
    {
      return false;
    }

  for (xmlAttr* attr = node->properties; attr; attr = attr->next)
    {
      if (strcmp ((const char*)attr->name, name) == 0)
        {
          return true;
        }
    }
  return false;
}

unsigned ceXmlElement::GetNumberOfChildren (const char* tagName) const
{
  unsigned num=0;
  if (!node)
    {
      return num;
    }

  bool testTagName = tagName != 0 && strlen(tagName) != 0;

  for (xmlNode* child = node->children; child; child = child->next)
    {
      if (child->type == XML_ELEMENT_NODE && 
          (!testTagName  ||
          strcmp ((const char*)child->name, tagName) == 0))
        {
          num++;
        }
    }

  return num;
}

ceXmlElement* ceXmlElement::GetChild (const char* tagName) const
{
	return GetChild (0, tagName);
}

ceXmlElement* ceXmlElement::GetChild (unsigned idx, const char* tagName) const
{
	if (!node)
  {
    return 0;
  }

  unsigned num=0;
  bool testTagName = tagName != 0 && strlen(tagName) != 0;

  for (xmlNode* child = node->children; child; child = child->next)
    {
      if (child->type == XML_ELEMENT_NODE && 
          (!testTagName  ||
          strcmp((const char*)child->name, tagName) == 0))
        {
          if (num == idx)
            {
              return new ceXmlElement (child);
            }
          num++;
        }
    }
  return 0;
}

int ceXmlElement::GetIntAttribute (const char* attributeName) const
{
	const char* val = GetAttribute (attributeName);
	if (val)
	{
		return atoi (val);
	}
	return 0;
}

float ceXmlElement::GetFloatAttribute (const char* attributeName) const
{
	const char* val = GetAttribute (attributeName);
	if (val)
	{
		return (float)atof (val);
	}
	return 0.0f;
}



